﻿Imports System.Text

Public Class clsDiagrammCreator

    Public Shared Function WriteFile(ByVal sFilename As String, ByVal diagramm()()() As Int32, ByVal projInfo As clsProject, Optional mover As Int32 = 0) As Boolean
        Try
            Dim sw As New IO.StreamWriter(sFilename, False, System.Text.Encoding.Default)
            Dim cr As New clsDiagrammCreator
            sw.WriteLine(cr.GenerateHtml(diagramm, projInfo, mover))
            sw.Close()
            cr = Nothing
            Return True
        Catch ex As Exception
            Throw
        End Try
    End Function
    Public Shared Function WriteOptFile(ByVal sfilename As String, ByVal projInfo As clsProject) As Boolean
        Try
            Dim sw As New IO.StreamWriter(sfilename, False, System.Text.Encoding.Default)
            Dim cr As New clsDiagrammCreator
            sw.WriteLine(String.Concat("n_res = ", projInfo.RenewableResources.Count, ";"))
            sw.WriteLine(String.Concat("rc = [", DicToString(projInfo.RenewableResources, ", "), "];"))
            sw.WriteLine(String.Concat("n_tasks = ", projInfo.TasksA.Count, ";"))
            sw.WriteLine(String.Concat("d = [", TaskDurToString(projInfo), "];"))
            sw.WriteLine(String.Concat("rr = [", ResToString(projInfo), "];"))
            sw.WriteLine(String.Concat("suc = [", PostToString(projInfo), "];"))
            sw.WriteLine(String.Concat("headt = [", PlanedToString(projInfo), "];"))
            sw.WriteLine(String.Concat("tailt = [", PlanedToString(projInfo), "];"))
            sw.Close()
            cr = Nothing
            Return True
        Catch ex As Exception
            Throw
        End Try
    End Function
    Private Function GenerateHtml(ByVal diagramm()()() As Int32, ByVal projInfo As clsProject, Optional ByVal mover As Int32 = 0) As String
        Try
            Dim Resname(projInfo.RenewableResources.Keys.Count - 1) As String
            For i As Int32 = 0 To projInfo.RenewableResources.Keys.Count - 1
                Resname(i) = projInfo.RenewableResources.Keys(i)
            Next
            Dim html As New StringBuilder("<html>")
            html.Append("<head>")
            ' html.Append("<script type='text/javascript' src='jquery-1.7.1-min.js'></script>")
            html.Append(GenerateCss(projInfo.TasksA.Count))
            'html.Append(GetActityJQ(projInfo))
            html.Append("</head>")
            html.Append("<body>")
            html.Append("<div>")
            html.Append(GenerateLegend(projInfo.TasksA, projInfo))
            html.Append("</div>")
            html.Append("<br/>")
            Dim j As Int32 = 0
            For Each dia()() As Int32 In diagramm
                html.Append("<div class='break'>")
                html.Append(DiagrammToHtml(dia, projInfo, mover).ToString)
                html.Append("</div>")
                html.Append("<p>")
                html.Append(Resname(j))
                html.Append("</p>")
                '   html.Append("<a href='javascript:Animate();'>Animate</a>")
                '  html.Append("<br/>")
                j += 1
            Next
            html.Append("</body>")
            html.Append("</html>")
            Return html.ToString
        Catch ex As Exception
            Throw
        End Try
    End Function
    Private Function GenerateCss(ByVal taskcount As Int32) As String
        Try
            Dim css As New StringBuilder("<style>")
            css.Append("table { border:1px solid #f00; }")
            css.Append(vbCrLf)
            css.Append(".break { page-break-before: always; }")
            css.Append(vbCrLf)
            css.Append(".col {height:15px; width:15px;border-left-style: dotted ; border-width: 0.1pt; border-color:  #DarkGray;}")
            css.Append(vbCrLf)
            css.Append(".itm0{height:15px; width:15px; background-color:white;border-style: dotted ; border-width: 0.1pt; border-color:  #DarkGray;}")
            css.Append(vbCrLf)
            For tasknr As Int32 = 1 To taskcount
                css.Append(String.Format(".itm{0}", tasknr))
                css.Append("{")
                css.Append(String.Format("height:15px; width:15px; background-color:{0}", GetColor(tasknr)))
                css.Append("}")
                css.Append(vbCrLf)
            Next
            css.Append("</style>")
            Return css.ToString
        Catch ex As Exception
            Throw
        End Try
    End Function
    Private Function GetRandomColor(ByVal key As Int32) As String
        Try
            If colors Is Nothing Then
                colors = New Dictionary(Of Int32, String)
            End If
            If colors.ContainsKey(key) Then
                Return colors(key)
            End If
            Dim col As Color = Color.FromArgb(Math.Min(Math.Round(Rnd() * 300), 255), Math.Min(key * 10, 255), Math.Min(Math.Round(Rnd() * 300), 255))
            colors.Add(key, System.Drawing.ColorTranslator.ToHtml(col).ToString())
            Return System.Drawing.ColorTranslator.ToHtml(col).ToString()
        Catch ex As Exception
            Throw
        End Try
    End Function
    Private Function GetColor(ByVal key As Int32) As String
        Try
            Return GetRandomColor(key)
        Catch ex As Exception
            Throw
        End Try
    End Function

    Private Function GenerateLegend(ByVal tasks As List(Of clsTask), ByVal projInfo As clsProject) As String
        Try
            Dim legend As New StringBuilder("<table border=1>")
            Dim header() As String = New String() {"Key", "Duration", "Pre", "Resource", "MPM-FAZ",
                                                   "MPM-FEZ", "MPM-SAZ",
                                                   "MPM-SEZ", "MPM-Puffer", "FAZ", "FEZ", "SAZ",
                                                   "SEZ", "Puffer", "PlanedAt"}
            legend.Append("<tr>")
            For Each head In header
                legend.Append("<td>")
                legend.Append(head)
                legend.Append("</td>")
            Next
            legend.Append("</tr>")
            For Each task As clsTask In tasks
                With task
                    legend.Append("<tr>")
                    Dim cols() As String = New String() {.Key.ToString, .Duration, ListToString(.Pre),
                                                         DicToString(.RenewableResources), .MPMFAZ, .MPMFEZ,
                                                         .MPMSAZ, .MPMSEZ, .MPMPuffer, .FAZ, .FEZ,
                                                         .SAZ, .SEZ, .Puffer, .PlanedAt}
                    Dim a As Int32 = 0
                    For Each col In cols
                        legend.Append(String.Format("<td {0}>", If(a > 0, "", String.Format("class='itm{0}'", task.Key))))
                        legend.Append(col)
                        legend.Append("</td>")
                        a += 1
                    Next
                End With
                legend.Append("</tr>")
            Next
            legend.Append("</table>")
            legend.Append("</br>")
            legend.Append("<table>")
            header = New String() {"MPM", "Fitness", "CriticalPath", "Resources", "Activity List"}
            legend.Append("<tr>")
            For Each head In header
                legend.Append("<td class='itm0'>")
                legend.Append(head)
                legend.Append("</td>")
            Next
            legend.Append("</tr>")
            legend.Append("<tr>")
            With projInfo
                Dim proj() As String = New String() {.MPMTime, .Fitness, Join(.CriticalPath.ToArray, "|"),
                                                     DicToString(.RenewableResources),
                                                     ListToString(.ActivtyList)}
                For Each col In proj
                    legend.Append("<td class='itm0'>")
                    legend.Append(col)
                    legend.Append("</td>")
                Next
            End With
            legend.Append("</tr>")
            legend.Append("</table>")
            Return legend.ToString
        Catch ex As Exception
            Throw
        End Try
    End Function
    Private Function GetActityJQ(ByVal projInfo As clsProject) As String
        Try
            Dim sb As New StringBuilder("<script> function Animate(){")
            sb.Append(" $('div').hide();$('.itm0').show();")
            Dim count As Int32 = projInfo.ActivtyList.Count - 1
            Dim x As Int32 = 0
            For Each act As Int32 In projInfo.ActivtyList
                sb.Append(String.Format("$('.itm{0}').fadeIn(800 ", act))
                If x < count Then
                    sb.Append(", function() {")
                End If
                x += 1
            Next
            x = 0
            For Each act As Int32 In projInfo.ActivtyList
                sb.Append(");")
                If x < count Then
                    sb.Append("}")
                End If
                x += 1
            Next
            sb.Append("} </script>")
            Return sb.ToString
        Catch ex As Exception
            Throw
        End Try
    End Function
    Public Function DiagrammToHtml(ByVal diagram()() As Int32, ByVal projInfo As clsProject, Optional mover As Int32 = 0) As StringBuilder
        Try
            Dim row = diagram.Length - 1



            Dim tab As New StringBuilder("<table cellpadding='0' cellspacing='0'>")
            For r As Int32 = row To 0 Step -1
                Dim col = projInfo.Fitness - 1 'diagram(r).Length - 1
                tab.Append("<tr>")
                tab.Append("<td>")
                tab.Append(r + 1)
                tab.Append("</td>")
                For c As Int32 = 0 To col

                    Dim tasknr As Int32 = 0
                    Dim tooltip As String = ""
                    If diagram(r)(c + mover) > 0 Then
                        tasknr = diagram(r)(c + mover).ToString
                        Dim task As clsTask = projInfo.TasksA(tasknr)
                        tooltip = "Task" & task.Key & ": Dur " & task.Duration & " Res: " & DicToString(task.RenewableResources) _
                        & " FAZ " & task.FAZ & " Puffer " & task.Puffer & " Pre " & ListToString(task.Pre) & " PlanedAt " & task.PlanedAt
                    End If
                    tab.Append("<td>")
                    tab.Append(String.Format("<div title='{1}' class='itm{0}'></div>", tasknr, tooltip))
                    tab.Append("</td>")
                Next
                tab.Append("</tr>")


            Next
            tab.Append("<tr><td></td>")
            For c As Int32 = 0 To projInfo.Fitness - 1 Step 10
                Dim span As Long = 10
                If span + c > projInfo.Fitness - 1 Then
                    span = projInfo.Fitness - c

                End If
                tab.Append("<td " & If(c = 0, "", "class='col'") & " colspan='" & span & "'>")
                If c = 0 Then
                    tab.Append("1")
                Else
                    tab.Append(c)
                End If
                tab.Append("</td>")
            Next
            tab.Append("</tr>")
            tab.Append("</table>")
            Return tab
        Catch ex As Exception
            Throw
        End Try
    End Function
End Class
